package net.ib.mtalk.test;

import java.io.UnsupportedEncodingException;

import net.ib.mntalk.protocol.Session;
import net.ib.mtalk.R;
import net.ib.mtalk.network.NetResultReceiver;
import net.ib.mtalk.network.TcpClient;
import net.ib.mtalk.network.TcpEnvelope;
import net.ib.mtalk.network.serverapi.Ping;
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;

public class GPBTestActivity extends Activity implements NetResultReceiver.Receiver, OnClickListener{
	
	Button buttonConnect;
	Button buttonPing;
	Button buttonClose;
	
	TextView textState;
	
	NetResultReceiver mReceiver;
	
	/**
	 * @see android.app.Activity#onCreate(Bundle)
	 */
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		
		setContentView(R.layout.activity_gpb_test);
		buttonConnect = (Button) findViewById(R.id.buttonConnect);
		buttonConnect.setOnClickListener(this);
		buttonPing = (Button) findViewById(R.id.buttonPing);
		buttonPing.setOnClickListener(this);
		buttonClose = (Button) findViewById(R.id.buttonClose);
		buttonClose.setOnClickListener(this);
		
		mReceiver = new NetResultReceiver(new Handler(), this);
	}

	@Override
	public void onNetResult(int resultCode, Object request, Object result) {
		TcpEnvelope rev = (TcpEnvelope) result;
		switch (rev.getMethodId()) {
		case net.ib.mtalk.network.MethodId.Session.Ping.Ping:
			pong((Session.PongRes)rev.getMessage());
			break;
		}
	}

	@Override
	public void onClick(View v) {
		switch(v.getId()) {
		case R.id.buttonConnect:
			TcpClient.reconnect();
			break;
		case R.id.buttonPing:
			ping();
			break;
		case R.id.buttonClose:
			TcpClient.close();
			break;
		}
	}
	
	/**
	 * 참조할 코드!
	 */
	public void ping() {
		try {
			Ping.ping("Hello World!!".getBytes("UTF-8"), mReceiver);
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
	}
	
	public void pong(Session.PongRes pongRes) {
		try {
			String toPrint = "pong: <" + pongRes.getResponseCode() + "> ";
			if (pongRes.hasOptions())
				toPrint = toPrint + pongRes.getOptions().toString("UTF-8");
			System.out.println(toPrint);
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
	}
	
	@Override
	public void onNetError(int resultCode, Object resultData) {
		// do nothing
	}
}
